#!/usr/bin/env python
from flask import Flask,render_template,request,jsonify
import subprocess


app = Flask(__name__,
            template_folder='view/pages',
            static_folder='view')

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/compiler/",methods=['post'])
def compiler():
    content = request.data

    with open("./test.c",'w',encoding='utf-8') as f:
        f.write(str(content,'utf-8'))

    cmd_order = 'gcc test.c -o test.out && test.out'
    cmd_p = subprocess.Popen(cmd_order, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    err = cmd_p.stderr.read()

    if len(err) == 0:
        cmd_result = ""
        for i in cmd_p.stdout.readlines():
            cmd_result += i.decode()

        return cmd_result.replace('\n',"<br/>")

    else:
        return str(err.decode('utf-8')).replace('test.c:',"")
